<template>
  <el-dialog
    title="新增员工"
    :visible="showDialog"
    @close="closeFn"
  >
    <!-- 表单 -->
    <el-form ref="form" :rules="rules" :model="formData" abel-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="邮箱" prop="username">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-row type="flex" justify="center">
        <el-button @click="submit">提交</el-button>
        <el-button @click="closeFn">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
<script>
import { addEmployee } from '@/api/employee'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        username: '', // 用户名
        email: '', // 邮箱
        password: '' // 密码
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/, message: '请輸入正确的格式', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^[a-zA-Z]\w{5,17}$/, message: '请輸入正确的格式', trigger: 'blur' }
        ]
      }
    }
  }, // 接收psMsg值
  // 表单校验
  methods: {
    // 确认
    submit() {
      this.$refs.form.validate(async bool => {
        if (bool) {
          // 校验通过
          await addEmployee(this.formData)
          this.$message({
            message: '新增成功',
            type: 'success'
          })
          // 关闭弹窗
          this.closeFn()
          // 刷新列表
          this.$emit('updateEvent')
        }
      })
    },
    // 关闭弹窗
    closeFn() {
      this.$emit('update:showDialog', false)
      // 清空数据
      this.formData = {
        username: '', // 用户名
        email: '', // 邮箱
        password: ''
      }
      // 清空校验规则
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style>

</style>
